package com.situ.mall.interceptor;

import com.situ.mall.pojo.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // /page/product/list
            // /page/cart/list
            // /cart/add?returnUri=/page/product/detail?id='+id
            String uri = request.getRequestURI();
            String returnUri = request.getParameter("returnUri");
            if (ObjectUtils.isEmpty(returnUri)) {
                response.sendRedirect("/page/login?returnUri=" + uri);
            } else {
                redirect(request, response);
            }
            return false;
        }

        return true;
    }

    private void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String returnUri = request.getParameter("returnUri");
        //获取当前请求的路径
        //logger.error("请求类型:"+request.getHeader("X-Requested-With"));
        response.setHeader("Access-Control-Expose-Headers", "REDIRECT,CONTEXTPATH");
        //告诉ajax我是重定向
        response.setHeader("REDIRECT", "REDIRECT");
        //告诉ajax我重定向的路径
        String url = "https://xxx.xxx.xxx/";//重定向路径
        response.setHeader("CONTEXTPATH", "/page/login?returnUri=" + returnUri);
        response.getWriter().write(1);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    }
}